package mspbots.hubspot.client.mailchimp;

import cn.hutool.crypto.digest.MD5;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.hubspot.client.mailchimp.client.MailChimpClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * data.connector.hubspot.api.mailchimp.ChimpMemberService
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/4/8
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class ChimpMemberService {

    private final MailChimpClient mailChimpClient;
    private final ObjectMapper objectMapper;

    public Mono<JsonNode> createOrUpdate(String email, Map<String,String> params){
        ObjectNode objectNode = this.objectMapper.createObjectNode();
        objectNode.put("email_address",email);
        objectNode.put("status_if_new","subscribed");
        objectNode.put("email_type","text");
        objectNode.putPOJO("merge_fields",params);
        String md5Email = MD5.create().digestHex(email);
        log.debug("Email md5 digest {}",md5Email);
        log.debug("Put member params {}",objectNode);
        return this.mailChimpClient.put(builder -> builder.path("/members/{email}").build(md5Email),objectNode);
    }
}
